package com.sgffsg.learn.javalib.thread;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author: lmk
 * @date: 2024/3/31
 * @desc: 生产者消费者模型阻塞队列实现
 */
public class ProducerConsumerModel3 {
    LinkedBlockingQueue<String> queue = new LinkedBlockingQueue(5);
    AtomicInteger number = new AtomicInteger(0);

    public static void main(String[] args) {
        ProducerConsumerModel3 pcm = new ProducerConsumerModel3();
        pcm.startTest();
    }

    public void startTest() {
        for (int i = 0; i < 3; i++) {
            Producer producer = new Producer("Producer-"+i);
            producer.start();
            Consumer consumer = new Consumer("Consumer-"+i);
            consumer.start();
        }
    }

    class Producer extends Thread {
        Producer(String name) {
            setName(name);
        }

        @Override
        public void run() {
            super.run();
            for (int i = 0; i < 10; i++) {
                try {
                    Thread.sleep(1000L);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                String product = "iphone编号：" + number.getAndIncrement();
                try {
                    queue.put(product);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println(Thread.currentThread().getName() + "生产了产品-" + product);
            }
            System.out.println(Thread.currentThread().getName()+"-本轮生产完成");
        }
    }

    class Consumer extends Thread {
        Consumer(String name) {
            setName(name);
        }

        @Override
        public void run() {
            super.run();
            for (int i = 0; i < 10; i++) {
                try {
                    Thread.sleep(1000L);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                String product = null;
                try {
                    product = queue.take();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println(Thread.currentThread().getName()+"购买了产品-" + product);
            }
            System.out.println(Thread.currentThread().getName()+"-本轮购买完成");
        }
    }

}
